package com.smssalama.storage.sms;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import javax.microedition.rms.RecordComparator;
import javax.microedition.rms.RecordFilter;

import com.smssalama.storage.framework.ObjectStorageException;
import com.smssalama.storage.framework.Storable;

public abstract class SMSMessage extends Storable {

	private static final Object COMPARE_TIMESTAMP = new Object();
	// private static final int COMPARE_PHONE_NUMBER = 2;

	private String phoneNumber;
	private long timestamp;

	public SMSMessage() {
	}

	public SMSMessage(String phoneNumber, long timestamp) {
		this.phoneNumber = phoneNumber;
		this.timestamp = timestamp;
	}

	public String getPhoneNumber() {
		return this.phoneNumber;
	}

	public long getTimestamp() {
		return this.timestamp;
	}

	protected void store(DataOutputStream stream) throws IOException,
			ObjectStorageException {
		stream.writeUTF(this.phoneNumber);
		stream.writeLong(this.timestamp);
	}

	protected void load(DataInputStream stream) throws IOException,
			ObjectStorageException {
		this.phoneNumber = stream.readUTF();
		this.timestamp = stream.readLong();
	}

	public static RecordFilter getFilter() {
		return SMSMessageFilter.getPassFilter();
	}

	public static RecordFilter getPhoneNumberFilter(String phoneNumber) {
		return new SMSMessageFilter(phoneNumber);
	}

	public int compareTo(Storable o) {
		return compareTo(o, SMSMessage.COMPARE_TIMESTAMP);
	}

	public int compareTo(Storable o, Object criteria) {
		if (!(o instanceof SMSMessage)) {
			return 0;
		}
		if (criteria == SMSMessage.COMPARE_TIMESTAMP) {
			long diff = this.timestamp - ((SMSMessage) o).timestamp;
			if (diff < 0) {
				return RecordComparator.PRECEDES;
			} else if (diff > 0) {
				return RecordComparator.FOLLOWS;
			} else {
				return RecordComparator.EQUIVALENT;
			}
		}
		return super.compareTo(o, criteria);
	}
}
